package com.fadadianqi.logistics.inventory.service;

import com.fadadianqi.logistics.inventory.dao.BatchDAO;
import com.fadadianqi.logistics.inventory.model.Batch;
import com.fadadianqi.logistics.inventory.model.Item;
import com.fadadianqi.logistics.sell.service.BillService;
import com.yeqiangwei.commons.util.Pagination;
import com.yeqiangwei.commons.util.ValidatorHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class BatchService {

    @Transactional
    public void update(Batch batch) {
        String batchId = batch.getId();
        List<Item> list = inventoryService.findByBatchId(batchId);
        if (ValidatorHelper.isNotEmpty(list)) {
            for (Item item : list) {
                item.setBatchId(batchId);
                item.setCost(batch.getCost());
                item.setDiscountRate(batch.getDiscountRate());
                item.setGoodsId(item.getGoodsId());
                item.setLastUpdateTime(new Date());
                item.setMemo(batch.getMemo());
                item.setPurchase(batch.getPurchase());
                inventoryService.update(item);
                updateSoldItems(item);
            }
        }
        batchDAO.update(batch);
    }

    private void updateSoldItems(Item item) {
        billService.updateSoldItems(item);
    }

    public Batch getById(String batchId) {
        return batchDAO.getById(batchId);
    }

    public int countById(String batchId) {
        // TODO Auto-generated method stub
        return 0;
    }

    public int countNormal(String batchId) {
        // TODO Auto-generated method stub
        return 0;
    }

    public List<Batch> findAll(String goodsId, String brandId,
                               String categoryId, Pagination pagination) {
        List<Batch> list = batchDAO.findAll(goodsId, categoryId, brandId, pagination);
        return list;
    }

    public int count(String goodsId, String brandId, String categoryId) {
        return batchDAO.count(goodsId, brandId, categoryId);
    }

    @Autowired
    private BatchDAO batchDAO;

    @Autowired
    private InventoryService inventoryService;

    @Autowired
    private BillService billService;
}
